<template>
  <div class="app-container">
    <el-container>
      <!-- 顶部搜索栏 -->
      <el-header>
        <el-row :gutter="20">
          <el-col :span="24" style="display: flex; align-items: center;">
            <!-- 搜索输入框 -->
            <el-input
              v-model="kwInput"
              placeholder="输入关键词进行筛选"
              class="input-with-select"
              clearable
              style="max-width: 600px;"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                :loading="serploading"
                @click="handleSerpSearch"
              >
                搜索
              </el-button>
            </el-input>
            <el-button
              icon="el-icon-search"
              :loading="serploading"
              @click="handleLocalSerpSearch"
            >
              本机搜索
            </el-button>
            <!-- 查看历史按钮，点击打开抽屉 -->
            <el-button
              type="primary"
              icon="el-icon-time"
              style="margin-left: 20px;"
              @click="drawerVisible = true"
            >
              查看历史
            </el-button>
          </el-col>
        </el-row>
      </el-header>

      <!-- 主内容：显示 SERP 结果 -->
      <el-main>
        <!-- 一行两列：左侧放文本框，右侧放表格等 -->
        <el-row :gutter="20">
          <!-- 左侧：Title / PAA / Related Questions / Related Search -->
          <el-col :span="12">
            <el-form label-position="top">
              <el-form-item label="所有Title">
                <el-input
                  type="textarea"
                  :rows="7"
                  :value="titlesText"
                  readonly
                />
              </el-form-item>

              <el-form-item label="PAA (People Also Ask)">
                <el-input
                  type="textarea"
                  :rows="5"
                  :value="paaText"
                  readonly
                />
              </el-form-item>

              <el-form-item label="Related Questions">
                <el-input
                  type="textarea"
                  :rows="5"
                  :value="relatedQuestionsText"
                  readonly
                />
              </el-form-item>

              <el-form-item label="Related Search">
                <el-input
                  type="textarea"
                  :rows="3"
                  :value="relatedSearchText"
                  readonly
                />
              </el-form-item>

              <!-- 改为用户可输入 semrush_variations -->
              <el-form-item label="semrush关键词变体">
                <el-input
                  v-model="semrush_variations"
                  type="textarea"
                  :rows="3"
                />
              </el-form-item>

              <!-- 改为用户可输入 semrush_questions -->
              <el-form-item label="semrush quesitons">
                <el-input
                  v-model="semrush_questions"
                  type="textarea"
                  :rows="3"
                />
              </el-form-item>

              <el-form-item label="Top 20 列表的URL">
                <div v-if="top20Urls.length === 0">
                  暂无数据
                </div>
                <div v-else>
                  <ul>
                    <li
                      v-for="(url, index) in top20Urls"
                      :key="index"
                      style="margin-bottom: 5px;"
                    >
                      <el-link
                        :href="url"
                        target="_blank"
                        type="primary"
                      >
                        {{ getDomain(url) }}
                      </el-link>
                    </li>
                  </ul>
                </div>
              </el-form-item>
            </el-form>
          </el-col>

          <!-- 右侧：AI生成标题的操作区 + 表格 -->
          <el-col :span="12">
            <el-select v-model="ai_prompt_id" placeholder="请选择">
              <el-option
                v-for="item in ai_options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <el-select v-model="engine" placeholder="请选择">
              <el-option
                v-for="item in engines"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <el-button :loading="ailoading" @click="handleAIGenerateTitles">生成标题</el-button>
            <el-button @click="handleGetPrompts">获取prompts</el-button>

            <!-- 在多选表格之上，添加一个复制按钮 -->
            <el-button
              type="primary"
              :disabled="multipleSelection.length === 0"
              style="margin-left: 10px;"
              @click="handleCopySelectedTitles"
            >
              复制选中标题
            </el-button>

            <el-table
              :data="topics"
              style="width: 100%; margin-top: 15px;"
              stripe
              border
              height="400"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                type="selection"
                width="55"
              />
              <el-table-column
                type="index"
                label="编号"
                width="60"
                :index="indexMethod"
              />
              <el-table-column
                prop="title"
                label="标题"
              />
            </el-table>
            <el-button
              v-if="topics.length > 0"
              style="display: inline-block; margin-right: 10px;"
              type="primary"
              :loading="ailoading"
              @click="handleTopicRank"
            >
              优先级分析
            </el-button>
            <el-button
              v-if="topics.length > 0"
              style="display: inline-block; margin-right: 10px;float: right"
              type="primary"
              icon="el-icon-delete"
              @click="handleRemoveSelected"
            >
              删除选择的标题
            </el-button>
            <div v-if="html_results.length" v-html="html_results" />
            <el-input v-if="prompts.length" v-model="prompts" type="textarea" />
          </el-col>
        </el-row>
      </el-main>
    </el-container>

    <!-- 抽屉：显示最近查询记录 -->
    <el-drawer
      title="最近查询历史（最多 100 条）"
      :visible.sync="drawerVisible"
      direction="rtl"
      size="30%"
      :close-on-press-escape="true"
      :append-to-body="true"
    >
      <div v-if="queryHistory.length === 0">
        暂无记录
      </div>
      <div v-else>
        <p>点击可再次搜索：</p>
        <el-tag
          v-for="(item, index) in queryHistory"
          :key="index"
          style="margin: 5px;"
          effect="plain"
          @click.native="handleTagClick(item.keyword)"
        >
          {{ item.keyword }} ({{ item.time }})
        </el-tag>

        <hr>
        <div
          v-for="(item, index) in queryHistory"
          :key="index"
          style="margin-top: 10px; border: 1px dashed #ccc; padding: 5px;"
        >
          <p>关键词：{{ item.keyword }}</p>
          <p>查询时间：{{ item.time }}</p>
          <p>SEM Rush Variations: {{ item.semrush_variations }}</p>
          <p>SEM Rush Questions: {{ item.semrush_questions }}</p>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { Post } from '@/api/eco/serp' // 根据你的项目路径修改
import { Get as GetAiPrompt } from '@/api/cms/aiprompt' // 根据你的项目路径修改
import { Post as GetAiContent } from '@/api/cms/openai'
import axios from 'axios'

export default {
  name: 'Serp',
  data() {
    return {
      ai_prompt_id: '',
      engine: 'Claude-3.5-Sonnet',
      engines: [
        { label: 'Claude-3.7-Sonnet', value: 'claude-3.7-sonnet' },
        { label: 'gpt-4o', value: 'gpt-4o' },
        { label: 'o3-high', value: 'o1-preview' }
      ],
      prompts: '',
      ai_options: [
        { label: '选择类型', value: '' },
        { label: '信息内容', value: '254' },
        { label: 'B2B列表式内容', value: '253' },
        { label: '品牌蹭流量', value: '14' }
      ],
      html_results: '',
      ailoading: false,
      serploading: false,

      // 让用户自行输入
      semrush_variations: '',
      semrush_questions: '',

      topics: [], // 显示在表格中的标题数组
      multipleSelection: [], // 表格中选中的行

      // 搜索输入框
      kwInput: '',
      // SERP 结果
      serp_data: {},

      // 抽屉
      drawerVisible: false,
      // 最近 100 条查询记录
      queryHistory: [],

      // 本地存储的所有数据（以关键词为key）
      storedQueryData: {},

      // 如果有分页之类可以保留
      pagesize: 10,
      page: 1,
      total: 0
    }
  },
  computed: {
    titlesText() {
      if (!this.serp_data.search_results) return ''
      return this.serp_data.search_results
        .map(item => item.title)
        .join('\n')
    },
    top20Urls() {
      if (!this.serp_data.search_results) return []
      return this.serp_data.search_results
        .slice(0, 20)
        .map(item => item.url)
    },
    paaText() {
      if (!this.serp_data.paa) return ''
      return this.serp_data.paa
        .map(item => item.question || item)
        .join('\n')
    },
    relatedQuestionsText() {
      if (!this.serp_data.related_questions) return ''
      return this.serp_data.related_questions.join('\n')
    },
    relatedSearchText() {
      if (!this.serp_data.related_searches) return ''
      return this.serp_data.related_searches.join('\n')
    }
  },
  created() {
    // 组件创建后，从 localStorage 中读取历史记录和存储数据
    this.loadQueryHistoryFromStorage()
    this.loadStoredQueryDataFromStorage()
  },
  methods: {
    indexMethod(index) {
      return index + 1
    },
    handleRemoveSelected() {
      this.topics = this.topics.filter(item => !this.multipleSelection.includes(item))
      // 同步到 storedQueryData
      this.saveTitlesToStoredData(this.kwInput, this.topics.map(item => item.title))
    },
    handleTopicRank() {
      this.ailoading = true
      GetAiContent({
        aiprompt_id: 255,
        kvs: [
          {
            topics_list: this.topics.map(item => item.title).join('\n'),
            target_keyword: this.kwInput,
            serp_data: JSON.stringify(this.serp_data),
            semrush_variations: this.semrush_variations,
            semrush_questions: this.semrush_questions
          }
        ],
        engine: this.engine,
        humanway: false
      }).then(response => {
        this.$notify.closeAll()
        if (response && response.content) {
          this.$notify({
            title: '成功',
            message: 'AI生成排序结果成功',
            type: 'success'
          })

          // 按换行符分割生成的新标题
          this.ailoading = false
          this.html_results = response.content
        }
      }).catch(error => {
        this.$notify.closeAll()
        this.ailoading = false
        this.$notify({
          title: '错误',
          message: 'AI失败：' + (error.message || '未知错误'),
          type: 'error'
        })
      })
    },
    /**
     * 生成新标题
     */
    handleAIGenerateTitles() {
      this.ailoading = true
      GetAiContent({
        aiprompt_id: this.ai_prompt_id,
        kvs: [
          {
            target_keyword: this.kwInput,
            exists_topics: this.topics.map(item => item.title).join('\n'),
            serp_data: JSON.stringify(this.serp_data),
            semrush_variations: this.semrush_variations,
            semrush_questions: this.semrush_questions
          }
        ],
        engine: this.engine,
        humanway: false
      }).then(response => {
        this.$notify.closeAll()
        if (response && response.content) {
          this.$notify({
            title: '成功',
            message: 'AI生成标题成功',
            type: 'success'
          })

          // 按换行符分割生成的新标题
          this.ailoading = false
          const newTitles = response.original_content
            .split('\n')
            .map(t => t.trim())
            .filter(t => t.length > 0)

          // 去重：仅保留当前 topics 里没有的标题
          const existingTitles = this.topics.map(item => item.title)
          const uniqueTitles = newTitles.filter(t => !existingTitles.includes(t))

          // 将新标题 push 到 topics
          uniqueTitles.forEach(t => {
            this.topics.push({ title: t })
          })

          // 同步到 storedQueryData
          this.saveTitlesToStoredData(this.kwInput, uniqueTitles)
        }
      }).catch(error => {
        this.$notify.closeAll()
        this.ailoading = false
        this.$notify({
          title: '错误',
          message: 'AI失败：' + (error.message || '未知错误'),
          type: 'error'
        })
      })
    },

    /**
     * 获取AI Prompt（如果需要）
     */
    handleGetPrompts() {
      GetAiPrompt(this.ai_prompt_id)
        .then(response => {
          this.prompts = response.data.prompt
          // 把{{serp_data}}替换成serp_data的JSON
          this.prompts = this.prompts.replace(/{{serp_data}}/g, JSON.stringify(this.serp_data))
          // 把[keyword]替换成关键词
          this.prompts = this.prompts.replace(/\[keyword\]/g, this.kwInput)
          // 把{{semrush_variations}}替换成semrush_variations
          this.prompts = this.prompts.replace(/{{semrush_variations}}/g, this.semrush_variations)
          // 把{{semrush_questions}}替换成semrush_questions
          this.prompts = this.prompts.replace(/{{semrush_questions}}/g, this.semrush_questions)
        })
        .catch(err => {
          console.error(err)
        })
    },
    handleLocalSerpSearch() {
      if (!this.kwInput) {
        this.$notify({
          title: '警告',
          message: '请输入关键词进行搜索',
          type: 'warning'
        })
        return
      }

      this.serploading = true

      axios.get('http://127.0.0.1:9000/search', { params: { keywords: this.kwInput }})
        .then(response => {
          this.serploading = false
          const data = response.data

          if (data.error) {
            this.$notify({
              title: '错误',
              message: data.error,
              type: 'error'
            })
            return
          }

          // 更新 SERP 数据
          this.serp_data = data
          console.log('本地搜索结果：', this.serp_data)
          // 更新各个文本区域
          // this.titlesText = this.serp_data.search_results.map(item => item.title).join('\n');
          // this.paaText = this.serp_data.related_questions
          // this.relatedQuestionsText = this.serp_data.related_questions
          // this.relatedSearchText = this.serp_data.related_searches

          // 更新 Top 20 URLs
          // this.top20Urls = this.serp_data.search_results.slice(0, 20).map(item => item.url);

          // 更新表格中的标题
          if (
            this.storedQueryData[this.kwInput] &&
          this.storedQueryData[this.kwInput].titles
          ) {
            this.topics = this.storedQueryData[this.kwInput].titles.map(t => ({ title: t }))
          } else {
            this.topics = []
          }

          // 存储到查询历史
          this.addQueryToHistory(
            this.kwInput,
            this.semrush_variations,
            this.semrush_questions
          )

          // 更新 storedQueryData
          if (!this.storedQueryData[this.kwInput]) {
            this.storedQueryData[this.kwInput] = {
              serp_data: {},
              titles: []
            }
          }
          this.storedQueryData[this.kwInput].serp_data = this.serp_data
          this.storedQueryData[this.kwInput].semrush_variations = this.semrush_variations
          this.storedQueryData[this.kwInput].semrush_questions = this.semrush_questions
          this.saveSerpDataToStoredData(this.kwInput, this.serp_data)

          // 同步到 localStorage
          this.saveStoredQueryDataToStorage()
        })
        .catch(error => {
          this.serploading = false
          const errorMessage = error.response && error.response.data && error.response.data.error
            ? error.response.data.error
            : error.message
          this.$notify({
            title: '错误',
            message: `搜索失败: ${errorMessage}`,
            type: 'error'
          })
        })
    },
    /**
     * 进行 SERP 搜索，获取后端数据
     */
    handleSerpSearch() {
      if (!this.kwInput) return
      this.serploading = true

      Post({ keyword: this.kwInput })
        .then(response => {
          this.serploading = false
          this.serp_data = response.result || {}

          // 这两行去掉，因 semrush_variations 和 semrush_questions 由用户自行输入
          // this.semrush_variations = this.serp_data.semrush_variations || ''
          // this.semrush_questions = this.serp_data.semrush_questions || ''

          console.log('后端返回的结果：', this.serp_data)

          // 存储到查询历史
          this.addQueryToHistory(
            this.kwInput,
            this.semrush_variations,
            this.semrush_questions
          )
          this.storedQueryData[this.kwInput]['semrush_variations'] = this.semrush_variations
          this.storedQueryData[this.kwInput]['semrush_questions'] = this.semrush_questions
          // 每次搜索后，同步 storedQueryData 的 serp_data
          this.saveSerpDataToStoredData(this.kwInput, this.serp_data)
          // 如果已经在本地存了标题，则读取出来展示；否则清空
          if (
            this.storedQueryData[this.kwInput] &&
            this.storedQueryData[this.kwInput].titles
          ) {
            this.topics = this.storedQueryData[this.kwInput].titles.map(t => ({ title: t }))
          } else {
            this.topics = []
          }
        })
        .catch(err => {
          this.serploading = false
          console.error(err)
        })
    },

    /**
     * 把搜索关键词和相关数据保存到查询历史
     */
    addQueryToHistory(keyword, semrushVariations, semrushQuestions) {
      if (!keyword) return

      // 去重：如果已存在同样 keyword，则删除旧的
      const oldIndex = this.queryHistory.findIndex(item => item.keyword === keyword)
      if (oldIndex !== -1) {
        this.queryHistory.splice(oldIndex, 1)
      }

      const historyItem = {
        keyword,
        semrush_variations: semrushVariations,
        semrush_questions: semrushQuestions,
        time: new Date().toLocaleString()
      }

      // 新记录插入头部
      this.queryHistory.unshift(historyItem)

      // 保持最大长度 100
      if (this.queryHistory.length > 100) {
        this.queryHistory.pop()
      }

      // 写入 localStorage
      this.saveQueryHistoryToStorage()
    },

    /**
     * 点击历史记录里的 tag，可以再次搜索
     */
    handleTagClick(keyword) {
      this.kwInput = keyword
      // this.handleSerpSearch()
      // 直接恢复历史记录
      this.kwInput = keyword
      this.serp_data = this.storedQueryData[keyword].serp_data
      this.topics = this.storedQueryData[keyword].titles.map(t => ({ title: t }))
      this.semrush_variations = this.storedQueryData[keyword].semrush_variations
      this.semrush_questions = this.storedQueryData[keyword].semrush_questions
      // 关闭抽屉
      this.drawerVisible = false
    },

    /**
     * 从 localStorage 读取历史记录
     */
    loadQueryHistoryFromStorage() {
      const stored = localStorage.getItem('serp_query_history')
      if (stored) {
        try {
          this.queryHistory = JSON.parse(stored)
        } catch (e) {
          console.warn('解析 localStorage 出错:', e)
          this.queryHistory = []
        }
      }
    },

    /**
     * 把 queryHistory 序列化后写入 localStorage
     */
    saveQueryHistoryToStorage() {
      localStorage.setItem('serp_query_history', JSON.stringify(this.queryHistory))
    },

    /**
     * 本地存储中保存：keyword -> { serp_data, titles }
     */
    saveSerpDataToStoredData(keyword, serpData) {
      if (!keyword) return
      // 如果该 keyword 尚无记录，初始化
      if (!this.storedQueryData[keyword]) {
        this.storedQueryData[keyword] = {
          serp_data: {},
          titles: []
        }
      }
      // 更新 serp_data
      this.storedQueryData[keyword].serp_data = serpData

      // 写入 localStorage
      this.saveStoredQueryDataToStorage()
    },

    /**
     * 保存标题到 storedQueryData
     */
    saveTitlesToStoredData(keyword, newTitles) {
      if (!keyword || !newTitles || newTitles.length === 0) return
      if (!this.storedQueryData[keyword]) {
        this.storedQueryData[keyword] = {
          serp_data: {},
          titles: []
        }
      }
      // 获取已有的 titles
      const existing = this.storedQueryData[keyword].titles
      // 添加去重后的新标题
      newTitles.forEach(title => {
        if (!existing.includes(title)) {
          existing.push(title)
        }
      })

      // 写回本地
      this.saveStoredQueryDataToStorage()
    },

    /**
     * 从 localStorage 加载 storedQueryData
     */
    loadStoredQueryDataFromStorage() {
      const dataStr = localStorage.getItem('serp_stored_query_data')
      if (dataStr) {
        try {
          this.storedQueryData = JSON.parse(dataStr)
        } catch (e) {
          console.warn('解析 storedQueryData 出错:', e)
          this.storedQueryData = {}
        }
      }
    },

    /**
     * 把 storedQueryData 序列化写回 localStorage
     */
    saveStoredQueryDataToStorage() {
      localStorage.setItem('serp_stored_query_data', JSON.stringify(this.storedQueryData))
    },

    /**
     * 处理表格勾选变化
     */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    /**
     * 点击“复制选中标题”按钮
     */
    async handleCopySelectedTitles() {
      if (this.multipleSelection.length === 0) return
      const text = this.multipleSelection.map(item => item.title).join('\n')
      try {
        await navigator.clipboard.writeText(text)
        this.$notify({
          title: '成功',
          message: '已复制所选标题',
          type: 'success'
        })
      } catch (e) {
        this.$notify({
          title: '错误',
          message: '复制失败，请手动复制',
          type: 'error'
        })
      }
    },

    getDomain(url) {
      try {
        const { hostname } = new URL(url)
        return hostname || url
      } catch (e) {
        return url
      }
    },

    // 如果有分页之类，可以在此处添加
    handleSizeChange(val) {
      this.pagesize = val
      // this.getList() // 根据需要实现
    },
    handlePageChange(val) {
      this.page = val
      // this.getList() // 根据需要实现
    }
  }
}
</script>

<style scoped>
.el-header, .el-footer {
  background-color: #fff;
  color: #333;
  text-align: left;
  line-height: 60px;
}

.el-main {
  background-color: #fff;
  color: #333;
  text-align: left;
  padding: 20px;
}
</style>
